import os
import Options

srcdir = '<%=srcdir%>'
blddir = '<%=blddir%>'
VERSION = '<%=version%>' 

def set_options(opt):
  opt.tool_options('compiler_cxx')
  opt.add_option('--with-ruby-archdir', type='string', dest='rubyarchdir', help='Specify directory where to install arch specific files')
  opt.add_option('--with-ruby-libdir',  type='string', dest='rubylibdir',  help='Specify alternate ruby library path')

def configure(conf):    
  conf.check_tool('compiler_cxx')
  conf.check_tool('node_addon')

  archdir = ['<%=Config::expand CONFIG['archdir']%>']
  cpppath = archdir
  <%if RUBY_VERSION >= "1.9.0"%>
  ruby_hdrdir = ['<%=Config::expand CONFIG['rubyhdrdir']%>']
  cpppath += ruby_hdrdir
  cpppath += [os.path.join(ruby_hdrdir[0], '<%=Config::expand CONFIG['arch']%>')]
  <%end%>

  conf.env.CPPPATH_RUBY += cpppath
  conf.env.LIB_RUBY = 'ruby'
  conf.env.LIBPATH_RUBY = ['<%=Config::expand CONFIG['libdir']%>']
  conf.env.LIBPATH_RUBY += archdir

  conf.check(header_name="ruby.h", includes=cpppath, errmsg='could not find ruby header file')
  conf.env.CCFLAGS_RUBY += ['<%=Config::expand CONFIG['CCDLFLAGS']%>']
  conf.env.shlib_PATTERN = '%s.<%=Config::expand CONFIG['DLEXT']%>'

  # ok this is really stupid, but the command and flags are combined.
  # so we try to find the first argument...
  flags = <%=(Config::expand CONFIG['LDSHARED']).split.inspect%>
  
  while flags and flags[0][0] != '-':
          flags = flags[1:]
  
  # we also want to strip out the deprecated ppc flags
  if len(flags) > 1 and flags[1] == "ppc":
          flags = flags[2:]
  
  conf.env.LINKFLAGS_RUBYEXT = flags
  conf.env.LINKFLAGS_RUBYEXT += ['<%=Config::expand CONFIG['LIBS']%>']
  conf.env.LINKFLAGS_RUBYEXT += ['<%=Config::expand CONFIG['LIBRUBYARG_SHARED']%>']
    
  if Options.options.rubyarchdir:
    conf.env.ARCHDIR_RUBY = Options.options.rubyarchdir
  else:
    conf.env.ARCHDIR_RUBY = '<%=Config::expand CONFIG['sitearchdir']%>'
  
  if Options.options.rubylibdir:
    conf.env.LIBDIR_RUBY = Options.options.rubylibdir
  else:
    conf.env.LIBDIR_RUBY = '<%=Config::expand CONFIG['sitelibdir']%>'
    
def build(bld):
  obj1 = bld.new_task_gen('cxx', 'objects', 'node_addon')
  obj1.target = 'wrapper'
  obj1.source = 'node_wrapper.cpp'

  ruby = bld.new_task_gen('cxx', 'shlib', 'node_addon')
  ruby.target = 'ruby'
  ruby.source = 'ruby.cpp <%=version_specific_source%>'
  ruby.add_objects = 'wrapper'
  ruby.uselib = 'RUBY'
